from itertools import islice
from collections import deque

def parse_player(input: str):
    player = deque()
    for line in input.splitlines()[1:]:
        player.append(int(line))
    return player

def play_game(player1: deque, player2: deque):
    histroy = set()
    while len(player1) != 0 and len(player2) != 0:
        key = f'{player1}:{player2}'
        if key in histroy:
            return True, player1
        histroy.add(key)
    
        top1, top2 = player1.popleft(), player2.popleft()
        if len(player1) >= top1 and len(player2) >= top2:
            player1_win, _ = play_game(deque(islice(player1, top1)), deque(islice(player2, top2)))
        else:
            player1_win = top1 > top2

        if player1_win:
            player1.append(top1)
            player1.append(top2)
        else: 
            player2.append(top2)
            player2.append(top1)
    
    return (False, player2) if len(player1) == 0 else (True, player1)

with open('input.txt') as file:
    parts = file.read().split('\n\n')
    player1 = parse_player(parts[0])
    player2 = parse_player(parts[1])

    _, winner = play_game(player1, player2)

    print( sum(v * (i + 1) for (i, v) in enumerate(reversed(winner))) )